/**
 * @计算一段文本的单词数目
 *
 * @author	 wangshikun <wangshikun2010@gmail.com>
 * @copyright	(c) 2012 wangshikun <wangshikun2010@gmail.com>
 * @license	http://www.opensource.org/licenses/mit-license.php The MIT License
 * @package	default
 * @subpackage	default
 */

#include <stdio.h>
#include <cs50.h>
#include <stdlib.h>

int countWords(const char string[]);
bool alphabetic(const char c);
void readline(char buffer[]);

int main(int argc, char *argv[]) {
	char text[81];
	int i = 0;
	bool s = false;

	printf("\a请输入一行单词：");

	while (!s) {
		readline(text);
		if (text[0] == '\0') {
			s = true;
		} else {
			i = i + countWords(text);
		}
	}

	printf("单词的个数是：%d\n", i);
}

//判断输入的字符
bool alphabetic(const char c) {
	if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
		return true;
	} else {
		return false;
	}
}

//计算输入单词的个数
int countWords(const char string[]) {
	int i, wordCount = 0;
	bool s = true;

	for (i=0; string[i] != '\0'; i++) {
		if (alphabetic(string[i])) {
			if (s) {
				++wordCount;
				s = false;
			}
		} else {
			s = true;
		}

	}

	return wordCount;
}

//从终端输入一行文字
void readline(char buffer[]) {
	char s;
	int i = 0;

	//将输入的字符放在一个数组里面
	do {
		s = getchar();
		buffer[i] = s;
		i++;
	} while (s != '\n');

	buffer[i-1] = '\0';
}
